package com.xxw.yygh.user.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxw.yygh.common.exception.YyghException;
import com.xxw.yygh.common.utils.JwtHelper;
import com.xxw.yygh.enums.AuthStatusEnum;
import com.xxw.yygh.enums.StatusEnum;
import com.xxw.yygh.model.user.Patient;
import com.xxw.yygh.model.user.UserInfo;
import com.xxw.yygh.user.dao.PatientDao;
import com.xxw.yygh.user.dao.UserInfoDao;
import com.xxw.yygh.user.service.PatientService;
import com.xxw.yygh.user.service.UserInfoService;
import com.xxw.yygh.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxw.yygh.vo.user.UserInfoQueryVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表(UserInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-03-01 11:28:56
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfo> implements UserInfoService {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1.先获取用户输入的手机号和验证码信息
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.对接收到的手机号和验证码做一个非空校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001,"手机号或验证码有误");
        }
        //3.对验证码做进一步确认
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        //如果为空或者不相等
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            throw  new YyghException(20001,"验证码有误");
        }
        String openid = loginVo.getOpenid();
        UserInfo userInfo = null;
        if (StringUtils.isEmpty(openid)) {
            //openid为空说明是手机号第一次登录
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("phone",phone);
            userInfo = baseMapper.selectOne(userInfoQueryWrapper);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setPhone(phone);
                baseMapper.insert(userInfo);
                userInfo.setStatus(1);
            }
        }else {
            //微信登录强制绑定手机号:首次使用微信登录并且强制绑定手机号才会走这个else
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("openid",openid);
            userInfo = baseMapper.selectOne(queryWrapper);

            QueryWrapper<UserInfo> phoneWrapper = new QueryWrapper<>();
            phoneWrapper.eq("phone",phone);
            UserInfo userInfo2 = baseMapper.selectOne(phoneWrapper);
            if (userInfo2 == null){
                //说明以前没有用手机登录过
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.updateById(userInfo);
            }else {
                //以前用手机号登录过
                //把微信信息赋值给之前用手机登录的信息
                userInfo2.setOpenid(userInfo.getOpenid());
                userInfo2.setNickName(userInfo.getNickName());
                baseMapper.updateById(userInfo2);

                //赋值完成，删除
                baseMapper.deleteById(userInfo.getId());
            }

        }

        //5.验证用户的status
        if (userInfo.getStatus() == 0) {
            throw  new YyghException(20001,"用户锁定中");
        }

        //6.返回用户信息
        Map<String,Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name",name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        return map;
    }

    @Override
    public UserInfo getUserInfo(Long userId) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));

        return userInfo ;
    }

    @Override
    public Page<UserInfo> getUserInfoPage(Integer pageNum, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        Page<UserInfo> page = new Page<>(pageNum,limit);
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(userInfoQueryVo.getKeyword())) {
            userInfoQueryWrapper.like("name",userInfoQueryVo.getKeyword()).or().eq("phone",userInfoQueryVo.getKeyword());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getStatus())) {
            userInfoQueryWrapper.eq("status",userInfoQueryVo.getStatus());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getAuthStatus())) {
            userInfoQueryWrapper.eq("auth_status",userInfoQueryVo.getAuthStatus());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeBegin())) {
            userInfoQueryWrapper.gt("create_time",userInfoQueryVo.getCreateTimeBegin());
        }
        if (!StringUtils.isEmpty(userInfoQueryVo.getCreateTimeEnd())) {
            userInfoQueryWrapper.lt("create_time",userInfoQueryVo.getCreateTimeEnd());
        }
        Page<UserInfo> page1 = baseMapper.selectPage(page, userInfoQueryWrapper);

       page1.getRecords().stream().forEach(item->{
           this.packageUserInfo(item);
       });

        return page1;
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if (status == 0 || status == 1) {
            UserInfo userInfo = baseMapper.selectById(id);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    @Override
    public Map<String, Object> detail(Long id) {

        UserInfo userInfo = baseMapper.selectById(id);
        QueryWrapper<Patient> patientQueryWrapper = new QueryWrapper<>();
        patientQueryWrapper.eq("user_id",id);
        List<Patient> patients = patientService.selectList(patientQueryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("patients",patients);

        return map;
    }

    private void packageUserInfo(UserInfo item) {

        Integer authStatus = item.getAuthStatus();
        Integer status = item.getStatus();

        item.getParam().put("statusString", StatusEnum.getStatusStringByStatus(status));
        item.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(authStatus));

    }
}

